package com.wusuowei.auth.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wusuowei.auth.service.ThreeUserService;
import com.wusuowei.ucenter.mapper.SysUserMapper;
import com.wusuowei.ucenter.model.po.SysUser;
import com.wusuowei.ucenter.model.po.SysUserRole;
import com.wusuowei.ucenter.service.ISysUserRoleService;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


/**
 * @description 第三方授权登录时，将用户信息保存到数据库中
 * @author LGY
 * @date 2023/03/31 17:20
 * @version 1.0.0
 */
@Service
public class ThreeUserServiceImpl implements ThreeUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysUserRoleService userRoleService;

    @Override
    @Transactional
    public SysUser addUser(AuthUser authUser) {
        //先取出unionid
        String unionid = authUser.getUuid();
        //根据unionid查询数据库
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUnionid, unionid));
        if (sysUser != null) {
            //该用户在系统存在
            sysUser.setLoginTime(LocalDateTime.now());
            sysUserMapper.updateById(sysUser);
            return sysUser;
        }
        sysUser = new SysUser();
        BeanUtils.copyProperties(authUser, sysUser);
        sysUser.setUnionid(unionid);
        sysUser.setPassword(unionid);
        sysUser.setStatus("0");//用户状态
        sysUser.setAvatarUrl(authUser.getAvatar());
        sysUser.setLoginTime(LocalDateTime.now());
        sysUserMapper.insert(sysUser);

        //设置默认角色
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(sysUser.getId().toString());
        sysUserRole.setRoleId(2);
        userRoleService.save(sysUserRole);

        return sysUser;
    }
}
